package com.fyzk.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.lottery.recommend_order.MyBaskOrderAdapter;
import com.fyzk.activity.lottery.recommend_order.MyRecommendBean;
import com.fyzk.activity.lottery.recommend_order.MyRecommendOrderBean;
import com.fyzk.activity.lottery.recommend_order.RecommendHelpActivity;
import com.fyzk.base.BaseFragment;
import com.fyzk.net.Commands;
import com.fyzk.view.DynamicLoadListener;
import com.fyzk.view.TopTitleView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * <p>
 *
 * @author Administrator
 * @mood
 * @description 晒单大厅Activity
 * @date 2018/9/20 11:20
 * </p>
 */
@ContentView(R.layout.activity_bask_order)
public class BaskOrderRootFragment extends BaseFragment implements OnRefreshListener, DynamicLoadListener {

    @ViewInject(R.id.baskOrderUI_topTitleView)
    TopTitleView mTopTitleView;
    @ViewInject(R.id.baskOrderUI_smartRefresh)
    SmartRefreshLayout mSmartRefresh;
    @ViewInject(R.id.baskOrderUI_recyclerView)
    RecyclerView mRecyclerView;

    // 类型（晒单：0；跟单：1）
    private int type = 0;
    private int page = 0;
    private int count = 20;
    private List<MyRecommendOrderBean> infos = new ArrayList<>();
    private MyBaskOrderAdapter mAdapter;
    private boolean isFirst = true;

    public static BaskOrderRootFragment newInstance() {

        Bundle args = new Bundle();

        BaskOrderRootFragment fragment = new BaskOrderRootFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inject = x.view().inject(this, inflater, container);
        initView();
        return inject;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        initListener();
    }

    private void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new MyBaskOrderAdapter(getContext(), infos, this);
        mRecyclerView.setAdapter(mAdapter);
        mTopTitleView.setVisibility(View.GONE);
    }

    private void initData() {
        onRefresh(mSmartRefresh);
    }

    private void initListener() {
        mTopTitleView.setOnTitleClickListener(this);
        mSmartRefresh.setOnRefreshListener(this);
    }

    @Override
    public void onLoadMore() {
        if (!isFirst) {
            page += infos.size();
            findRecommendedUserOrders(false);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isFirst = true;
        page = 0;
        findRecommendedUserOrders(false);
    }

    /**
     * 晒单个人详情查询
     *
     * @param showProgress
     */
    private void findRecommendedUserDetail(boolean showProgress) {
        httpPostJson(CommandUtil.FINDRECOMMENDEDUSERDETAIL, Commands.FINDRECOMMENDEDUSERDETAIL, null, showProgress);
    }

    /**
     * 个人晒单列表
     *
     * @param showProgress
     */
    private void findRecommendedUserOrders(boolean showProgress) {
        JSONObject request_json = new JSONObject();
        try {
            // 类型（晒单：0；跟单：1）
            request_json.put("type", type);
            request_json.put("startLine", page);
            request_json.put("maxLine", count);
            httpPostJson(CommandUtil.FINDRECOMMENDEDUSERORDERS, Commands.FINDRECOMMENDEDUSERORDERS, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);

        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDUSERDETAIL:
                MyRecommendBean userInfor = JSON.parseObject(resultBean.getData(), MyRecommendBean.class);
                MyRecommendOrderBean orderBean = new MyRecommendOrderBean();
                orderBean.setItem("head");
                orderBean.setUserBean(userInfor);
                infos.add(0, orderBean);
                mAdapter.setInfos(infos, type);
                break;
            case CommandUtil.FINDRECOMMENDEDUSERORDERS:
                List<MyRecommendOrderBean> beans = JSON.parseArray(resultBean.getData(), MyRecommendOrderBean.class);
                isFirst = false;
                if (page == 0) {
                    infos.clear();
                    infos.addAll(beans);
                    mSmartRefresh.finishRefresh();
                    if (beans.isEmpty()) {
                        mAdapter.setInfos(false);
                    } else {
                        mAdapter.setInfos(true);
                    }
                    findRecommendedUserDetail(false);
                } else {
                    if (beans == null || beans.size() == 0) {
                        mAdapter.setInfos(false);
                    } else {
                        infos.addAll(beans);
                        mAdapter.setInfos(true);
                    }
                }

                break;
        }
    }

    @Override
    public void onFailure(int requestCode, String errorCode, String message) {
        if (errorCode.equals("900003")) { // 数据为空
            mSmartRefresh.finishRefresh();
            mAdapter.setInfos(false);
        } else {
            mSmartRefresh.finishRefresh();
            mAdapter.setInfos(false);
            super.onFailure(requestCode, errorCode, message);
        }
    }

    @Override
    public void onRightClick() {
        Intent intent = new Intent(getContext(), RecommendHelpActivity.class);
        startActivity(intent);
    }
}
